
package forms;

import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import models.PointOfSaleModel;

/**
 *
 * @author ly
 */
public class PointOfSale extends javax.swing.JFrame {
    String cname;  
    PointOfSaleModel db;
    DefaultTableModel model;
    String username="";
    String userid="";
    public PointOfSale() {
        initComponents();
        db=new PointOfSaleModel();
        btndelete.setEnabled(false);
        btnupdate.setEnabled(false);       
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtid = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtqty = new javax.swing.JTextField();
        btnadd = new javax.swing.JButton();
        btndelete = new javax.swing.JButton();
        btnupdate = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        table_sale = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        btnbuy = new javax.swing.JButton();
        txttotal = new javax.swing.JLabel();

        setTitle("Point Of Sale");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jLabel1.setText("Product ID:");

        jLabel2.setText("Qty");

        btnadd.setText("Add");
        btnadd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnaddActionPerformed(evt);
            }
        });

        btndelete.setText("Delete");
        btndelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btndeleteActionPerformed(evt);
            }
        });

        btnupdate.setText("Update");
        btnupdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnupdateActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtid, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtqty, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnadd, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btndelete, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnupdate, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addComponent(jLabel1))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(txtid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addComponent(jLabel2))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(txtqty, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnadd)
                        .addComponent(btndelete)
                        .addComponent(btnupdate)))
                .addContainerGap())
        );

        table_sale.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Name", "Unit Price", "Qty", "Category"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        table_sale.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                table_saleMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(table_sale);

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel3.setText("Total:");

        btnbuy.setText("Buy Now");
        btnbuy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnbuyActionPerformed(evt);
            }
        });

        txttotal.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1037, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(797, 797, 797)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(txttotal, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap())
                            .addComponent(btnbuy, javax.swing.GroupLayout.Alignment.TRAILING)))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 74, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 395, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(txttotal, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnbuy)
                .addGap(13, 13, 13))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents
    private void clearForm(){
        this.txtid.setText("");
        this.txtqty.setText("");
        this.btndelete.setEnabled(false);
        this.btnupdate.setEnabled(false);
        this.btnadd.setEnabled(true);
    }
    private void updateproduct(){
        try{
            
            model = (DefaultTableModel) table_sale.getModel();
            int nRow = model.getRowCount();   
            int t=0,in=0,out=0,pro_in=0,pro_out=0,id=0;
            for (int i = 0 ; i < nRow ; i++){
                t = Integer.parseInt(model.getValueAt(i,3).toString());
                id = Integer.parseInt(model.getValueAt(i,0).toString());
                
                String selsql="select pro_id,pro_qty_in,pro_qty_out from products where pro_id='"+id+"'";
                ResultSet rs = db.select(selsql);
               if(rs.next()){
                   in=rs.getInt("pro_qty_in");
                   out=rs.getInt("pro_qty_out");
                   pro_in = in - t;
                   pro_out= out + t;
               }
               String sqlupdate="UPDATE products SET pro_qty_in='"+pro_in+"',pro_qty_out='"+pro_out+"' WHERE pro_id='"+id+"'"; 
                 db.update(sqlupdate); 
                 
            }
            
        }catch(Exception e){JOptionPane.showMessageDialog(null, e);}
       
    }
   private void transactions(){
            
       try{
            model = (DefaultTableModel) table_sale.getModel();
            int nRow = model.getRowCount();   
            int id=0,qty=0;
            for (int i = 0 ; i < nRow ; i++){
                id = Integer.parseInt(model.getValueAt(i,0).toString());
                qty = Integer.parseInt(model.getValueAt(i,3).toString());
                String sql="INSERT INTO transactions(tra_qty,tra_typeid,tra_productid,tra_date) VALUES ('"+qty+"',2,'"+id+"',NOW())";
                db.insert(sql);
            
            }
            
       }catch(Exception e){JOptionPane.showMessageDialog(null,e);}
   }
    private void addpro(){ 
        try{
            String sql="select * from products where pro_id ='"+txtid.getText()+"'";
            ResultSet rs = db.select(sql);
            if(rs.next()){
                if(Integer.parseInt(txtqty.getText().toString())>rs.getInt("pro_qty_in")){
                    JOptionPane.showMessageDialog(null,"Product Qty is "+rs.getInt("pro_qty_in")+"");
                }else{
                 int id = rs.getInt("pro_id");
                 String name = rs.getString("pro_name");
                 int price = rs.getInt("pro_price");
                 int categoryid = rs.getInt("pro_categoryid");
                 
                String sqlc="select cat_name from categories where cat_id='"+categoryid+"'";
                ResultSet rsc = db.select(sqlc);
            if(rsc.next()){
               cname = rsc.getString("cat_name");
    
            }else{cname="null";} 
                   
            model = (DefaultTableModel) table_sale.getModel();
            boolean ck=false;
            int nRow = model.getRowCount();   
            int t=0;
            int index=0;
            for (int i = 0 ; i < nRow ; i++){
                t = Integer.parseInt(model.getValueAt(i,0).toString());
                if(Integer.parseInt(txtid.getText().toString())==t){
                       ck=true;
                       index=i;
                       break;
                    }else{ck=false;}
            }
         if(ck==false){  
         model.addRow(new Object[]{id,name,price,txtqty.getText(),cname});
         }else{

                model.removeRow(index);
                model.addRow(new Object[]{id,name,price,txtqty.getText(),cname});
                }
         
         }   
            }else{
                JOptionPane.showMessageDialog(null,"Product ID Null");
            }
           
        }catch(Exception e){JOptionPane.showMessageDialog(null,e);} 
    }
    private void total(){
        model = (DefaultTableModel) table_sale.getModel();
        int nRow = model.getRowCount();   
        int t=0;
        for (int i = 0 ; i < nRow ; i++){
            t += Integer.parseInt(model.getValueAt(i,2).toString())* Integer.parseInt(model.getValueAt(i,3).toString());
         
            }
        String rt ="$ "+t;
        txttotal.setText(rt);
    
    }
    private void updatepro(){
       try{
        String sql="select pro_id,pro_qty_in from products where pro_id='"+txtid.getText()+"'";
        ResultSet rs = db.select(sql);
        if(rs.next()){
            if(Integer.parseInt(txtqty.getText().toString()) < rs.getInt("pro_qty_in")){
                 model = (DefaultTableModel) table_sale.getModel();
                     model.setValueAt(txtqty.getText(),table_sale.getSelectedRow(),3); 
             }else{
                    JOptionPane.showMessageDialog(null,"Product is "+rs.getInt("pro_qty_in")+"");
                }
            }
        
        }catch(Exception e){
              JOptionPane.showMessageDialog(null,e);
              
                }            
    }
    private void deletepro(){
        model = (DefaultTableModel) table_sale.getModel();
            model.removeRow(table_sale.getSelectedRow());
    }
    private void invoices(){
        try{
            
            String sql="INSERT INTO invoices(inv_date, inv_userid) VALUES ('"+userid+"',NOW())";
            db.insert(sql);
        
        }catch(Exception e){JOptionPane.showMessageDialog(null, e);}
    }
    private void btnaddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnaddActionPerformed
       this.addpro();
       this.clearForm();
       this. total();
    }//GEN-LAST:event_btnaddActionPerformed

    private void btndeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btndeleteActionPerformed
        this.deletepro();
        this.clearForm();
        this.total();
        
    }//GEN-LAST:event_btndeleteActionPerformed

    private void btnupdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnupdateActionPerformed
       this.updatepro();
       this.clearForm();
       this.total();
       
    }//GEN-LAST:event_btnupdateActionPerformed

    private void btnbuyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnbuyActionPerformed
       
    int opcion = JOptionPane.showConfirmDialog(null, "Are you sure", "Confirm", JOptionPane.YES_NO_OPTION);
        if (opcion == 0) { //The ISSUE is here
            this.updateproduct();
            this.transactions();
            model = (DefaultTableModel) table_sale.getModel();
            model.removeRow(opcion);
            txttotal.setText("");
        } else {
             System.out.print("no");
        }


    }//GEN-LAST:event_btnbuyActionPerformed

    private void table_saleMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_table_saleMouseClicked
         model = (DefaultTableModel) table_sale.getModel();
         txtid.setText(model.getValueAt(table_sale.getSelectedRow(),0).toString());
         txtqty.setText(model.getValueAt(table_sale.getSelectedRow(),3).toString());
         btndelete.setEnabled(true);
         btnupdate.setEnabled(true);
         btnadd.setEnabled(false);
    }//GEN-LAST:event_table_saleMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PointOfSale.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PointOfSale.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PointOfSale.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PointOfSale.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PointOfSale().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnadd;
    private javax.swing.JButton btnbuy;
    private javax.swing.JButton btndelete;
    private javax.swing.JButton btnupdate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table_sale;
    private javax.swing.JTextField txtid;
    private javax.swing.JTextField txtqty;
    private javax.swing.JLabel txttotal;
    // End of variables declaration//GEN-END:variables
}
